﻿/******************************************************************************
 *  Author：       Commscope ITDC Suzhou Web Team 
 *  CreateDate：   21/02/2012 2:28:21 PM
 *
 *
 ******************************************************************************/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Web.UI;

namespace EasyDLL.Web.UI
{
    public class ControlWrapper
    {
        /// <summary>
        /// 尝试获得一个控件的值
        /// </summary>
        /// <param name="control"></param>
        /// <returns></returns>
        public static object GetControlValue(Control control)
        {
            return GetControlValuePropertyInfo(control).GetValue(control, null).ToString();
        }

     
        /// <summary>
        /// 尝试给一个控件赋值
        /// </summary>
        /// <param name="control"></param>
        /// <param name="value"></param>
        public static void SetControlValue(Control control, object value)
        {
            GetControlValuePropertyInfo(control).SetValue(control, value, null);
        }

        #region 私有方法 

        /// <summary>
        /// 获得一个控件的值属性（比如TextBox的Text属性）的PropertyInfo信息
        /// </summary>
        /// <param name="control"></param>
        /// <returns></returns>
        private static PropertyInfo GetControlValuePropertyInfo(Control control)
        {
            string valuePropertyName = "Text"; //默认的value属性是Text
            //如果控件实现了ControlValuePropertyAttribute属性，那么就读取这个属性指定的值
            //标准的asp.net控件一般都实现了这个attribute，第三方的则不一定
            object[] customAttributes = control.GetType().GetCustomAttributes(typeof(ControlValuePropertyAttribute), true);
            if (customAttributes.Length > 0 && customAttributes[0] != null)
            {
                ControlValuePropertyAttribute valuePropertyAttributeName =
                    customAttributes[0] as ControlValuePropertyAttribute;
                if (valuePropertyAttributeName != null)
                {
                    valuePropertyName = valuePropertyAttributeName.Name;
                }
            }
            PropertyInfo valuePropertyInfo = control.GetType().GetProperty(valuePropertyName);
            if (valuePropertyInfo == null)
            {
                throw new TargetException("没有取到值");
            }
            return valuePropertyInfo;
        }

        #endregion
    }
}
